package com.example.rustfs.controller;

import com.example.rustfs.dto.ApiResponse;
import com.example.rustfs.service.ChunkUploadService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 分片上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/chunk")
@RequiredArgsConstructor
public class ChunkUploadController {
    
    private final ChunkUploadService chunkUploadService;
    
    /**
     * 初始化分片上传
     */
    @PostMapping("/init")
    public ApiResponse<Map<String, Object>> initUpload(
            @RequestParam String fileName,
            @RequestParam(required = false, defaultValue = "") String filePath,
            @RequestParam Long totalSize,
            @RequestParam Integer totalChunks,
            HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            Map<String, Object> result = chunkUploadService.initChunkUpload(userId, fileName, filePath, totalSize, totalChunks);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("初始化分片上传失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 上传分片
     */
    @PostMapping("/upload")
    public ApiResponse<Map<String, Object>> uploadChunk(
            @RequestParam String uploadId,
            @RequestParam Integer chunkIndex,
            @RequestParam MultipartFile file) {
        try {
            Map<String, Object> result = chunkUploadService.uploadChunk(uploadId, chunkIndex, file);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("上传分片失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取上传进度
     */
    @GetMapping("/progress/{uploadId}")
    public ApiResponse<Map<String, Object>> getProgress(@PathVariable String uploadId) {
        try {
            Map<String, Object> result = chunkUploadService.getUploadProgress(uploadId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取上传进度失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 取消上传
     */
    @DeleteMapping("/cancel/{uploadId}")
    public ApiResponse<String> cancelUpload(@PathVariable String uploadId) {
        try {
            chunkUploadService.cancelUpload(uploadId);
            return ApiResponse.success("上传已取消");
        } catch (Exception e) {
            log.error("取消上传失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
}

